﻿using System;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;
using SpiderPlatform.Dao;
using SpiderPlatform.Entity;
using Yamibuy.Framework.Core.Tools;
namespace SpiderPlatform.Service
{
    public class RedMallService
    {
        ItemDao dao;
        public DateTime? CurrentDay { get; set; }

        public DateTime TodayTime
        {
            get
            {

                DateTime todaytime = DateTime.Today;
                if (CurrentDay.HasValue)
                {
                    todaytime = CurrentDay.Value;
                }
                return todaytime;
            }
        }

        public RedMallService() {
            dao = new ItemDao();
        }
        string listUrl = "https://www.webooook.com/webooook/hmall/v2/common/deallist?dLatitude=0&dLongitude=0&dealclass={0}&dealtype=-1&keyword=&sAppType=HUSER&sAppVer=H2.8.0&sCountry=CA&sLang=zh&sTermId=4AEE5B48-E008-4A87-9EFD-6F9B4689AD4D&sTermType=iPhone7%2C2&sTermVer=iOS%3A10.2.1&sort=1&start={1}&tTermTime=2018-06-30T18%3A49%3A37-0700";
        string singleUrl = "https://www.webooook.com/webooook/hmall/v2/common/dealinfo?dLatitude=0&dLongitude=0&id={0}&sAppType=HUSER&sAppVer=H2.8.0&sCountry={1}&sLang=en&sTermId=4AEE5B48-E008-4A87-9EFD-6F9B4689AD4D&sTermType=iPhone7%2C2&sTermVer=iOS%3A10.2.1&tTermTime=2018-06-29T10%3A14%3A00-0700";
        public void doWork()
        {

            RedMallResult listResult = new RedMallResult();
            RedMallResult singleResult = new RedMallResult();
            HttpClient client = new HttpClient();
            List<ChannelItemHistoryEntity> hisList = new List<ChannelItemHistoryEntity>();
            var itemlist = dao.QueryChannelItem(4);

            for (int dealclass = 1; dealclass < 13; dealclass++)
            {
                int start = 0;
                do
                {
                    var listStr = client.GetStringAsync(string.Format(listUrl, dealclass, start)).Result;
                    listResult = Newtonsoft.Json.JsonConvert.DeserializeObject<RedMallResult>(listStr);
                    if (listResult != null)
                    {
                        Logger.Info($"当前start:{start},count:{listResult.entity.body.count}");
                        if (listResult.status == 200 && listResult.entity.body.count > 0)
                        {
                            foreach (var item in listResult.entity.body.l_deal_info)
                            {
                                // item.deal_id = "2c0273af-f7ee-421f-bbc4-959883cd8d19";
                               // Logger.Info($"dealclass:{dealclass} start:{start} processing {item.deal_seq_id}");
                                var Str = client.GetStringAsync(string.Format(singleUrl, item.deal_id, "CA")).Result;
                                singleResult = Newtonsoft.Json.JsonConvert.DeserializeObject<RedMallResult>(Str);
                                if (singleResult.entity.body.deal_info == null || singleResult.entity.body.deal_info.sale_deal_info == null)
                                {
                                    Logger.Info("next");
                                    continue;
                                }
                                singleResult.entity.body.deal_info.sale_deal_info.deal_id = item.deal_id;
                                var info = singleResult.entity.body.deal_info.sale_deal_info;
                                if (!string.IsNullOrEmpty(info.description))
                                {
                                    info.brand = trimContent(Regex.Match(info.description, "(【品牌】.+?<br>)|(品牌.+?<br>)").Value, "品牌");
                                    info.size = trimContent(Regex.Match(info.description, "(【数量】.+?<br>)|(数量.+?<br>)").Value, "数量");
                                    info.extend = trimContent(Regex.Match(info.description, "(【尺寸】.+?<br>)|(尺寸.+?<br>)").Value, "尺寸");
                                    info.country = trimContent(Regex.Match(info.description, "(【产地】.+?<br>)|(产地.+?<br>)").Value, "产地");
                                }
                                var temp = itemlist.FirstOrDefault(p => p.channel_sku == item.deal_id);
                                decimal regular_price = decimal.Parse(singleResult.entity.body.deal_info.sale_deal_info.regular_price);
                                decimal price = decimal.Parse(singleResult.entity.body.deal_info.sale_deal_info.price);
                                price = price * 0.7618m;
                                hisList.Add(new ChannelItemHistoryEntity
                                {
                                    channel_id = 4,
                                    channel_sku = singleResult.entity.body.deal_info.sale_deal_info.deal_id,
                                    score = 0,
                                    is_instock = singleResult.entity.body.deal_info.sale_deal_info.total_quantity,
                                    reviews = 0,
                                    price = regular_price > 0 && regular_price < price ? regular_price : price,
                                    title = singleResult.entity.body.deal_info.sale_deal_info.name,
                                    link = string.Empty,
                                    images = "https://www.webooook.com/webooook/hmall/v1/common/image?id="+singleResult.entity.body.deal_info.sale_deal_info.photo,
                                    description = item.description,
                                    sku = temp == null ? 0 : temp.sku
                                });
                            }
                        }
                        start = start + listResult.entity.body.count;
                    }
                    else
                    {
                        Logger.Info($"请求异常:{listStr},当前start:{start}");
                        break;
                    }

                }
                while (listResult.status == 200 && listResult.entity.body.more);
            }
            Logger.Info($"开始商品排重...，共{hisList.Count}条");
            hisList = hisList.Distinct(new ChannelItemHistoryComparer()).ToList();
            Logger.Info($"商品排重后...，共{hisList.Count}条");
            Logger.Info($"开始导入商品信息...，共{hisList.Count}条");
            dao.CreateChannelItemHistory(hisList);
            var hisExists = dao.QueryChannelItemBySku(4, hisList.Select(p => p.channel_sku).ToList());
            //检查是否有新的商品出现
            var diffList = hisList.Except(hisExists, new ChannelItemHistoryComparer());
            //记录新的item   
            var newItemList = diffList.ToList().ToTypeList<ChannelItemHistoryEntity, ChannelItemEntity>();
            Logger.Info($"检查新商品...，共{newItemList.Count}条");
            if (newItemList.Count > 0)
            {
                Logger.Info($"导入新商品step1...");
                dao.CreateChannelItem(newItemList);
                var realList = diffList.ToList();
                Logger.Info($"导入新商品step2...");
                dao.CreateChannelItemRealTime(realList);
            }
            Logger.Info($"更新商品信息...");
            dao.UpdateChannelItemRealTime(hisList);
            Logger.Info("任务完成");
        }
       
        private string trimContent(string source, string key)
        {
            return source.Replace("【" + key + "】", string.Empty).Replace(key, string.Empty).Replace(":", string.Empty).Replace("：", string.Empty).Replace("<br>", string.Empty);
        }      
    }
}
